package com.dolphin.artifact.common.db;

import com.dolphin.artifact.common.utils.SpringUtil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MybatisConfiguration extends MybatisAutoConfiguration {

    @Bean
    public SqlSessionFactory sqlSessionFactorys() throws Exception {
        return super.sqlSessionFactory(roundRobinDataSouceProxy());
    }

    @Bean
    public DynamicDataSource roundRobinDataSouceProxy() {
        DynamicDataSource proxy = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        targetDataSources.put("dataSourceWrite", SpringUtil.getBean("dataSourceWrite"));
        targetDataSources.put("dataSourceRead", SpringUtil.getBean("dataSourceRead"));
        proxy.setTargetDataSources(targetDataSources);
        proxy.setDefaultTargetDataSource(SpringUtil.getBean("dataSourceWrite"));
        return proxy;
    }
}